layui.use(['element', 'table', 'tree', 'zltreemenu', 'zlSelectEx', 'zlpoptree', 'zlContext', 'zlPopSourceExt', 'zlConfig', 'zlSelecttree', 'zlPopSourceForm'], function (exports) {
    var $ = layui.$
        , zlContext = layui.zlContext
        , zltreemenu = layui.zltreemenu
        , layer = layui.layer
        , table = layui.table
        , zlConfig = layui.zlConfig
        , statusName = zlConfig.global.result.statusName
        , msgName = zlConfig.global.result.msgName
        , dataName = zlConfig.global.result.dataName
        , OK = zlConfig.global.result.okState
        , form = layui.form
        , zlpoptree = layui.zlpoptree
        , zlPopSourceForm = layui.zlPopSourceForm
        , zlPopSourceExt = layui.zlPopSourceExt
        , coreTable = function () {
        };

    var formindex,
        authtree,
        roletree,
        index,
        newFormObj = {},
        isloadsearch = false;

    // 机构区域 目录树渲染
    var orgtreeObj = zltreemenu.render('orgtree', {
        dataurl: layui.cache['contentPath'] + "/manager/coreroleauth/queryOrgddata",
        type: "get",
        tableId: 'tbField',
        isMove: false
    }, {
        onAsyncSuccess: function (event, treeId, treeNode, msg) {
            orgtreeObj.selectNode(orgtreeObj.getNodes()[0]);
            $('#' + orgtreeObj.getNodes()[0].tId + '_a').click();
        },
        onClick: function (event, treeId, treeNode) {
            $('input[name="ORGIDTEMP"]').val(treeNode.RWID);
            // 角色区域 目录树渲染
            roletree = zltreemenu.render('roletree', {
                dataurl: layui.cache['contentPath'] + "/manager/coreroleauth/queryRole?isall=true&ORGID=" + treeNode.RWID,
                type: "get",
                isMove: false,
                pIdKey: null,
                search: false,
                dataFilter: function (treeId, parentNode, responseData) {
                    if (responseData[statusName] == OK) {
                        var data = responseData[dataName];
                        // 更换图标
                        for (var i = 0; i < data.length; i++) {
                            data[i].icon = layui.cache['contentPath'] + "/static/image/role.png";
                        }
                        return data;
                    } else {
                        zlContext.errorMsg(responseData[msgName]);
                    }
                    return responseData;
                }
            }, {
                onAsyncSuccess: function (event, treeId, treeNode, msg) {
                    roletree.selectNode(roletree.getNodes()[0]);
                    $('#' + roletree.getNodes()[0].tId + '_a').click()
                },
                onClick: function (event, treeId, treeNode) {
                    rendertable();
                    // 对应角色的数据表格下方权限展示区域 树结构渲染
                    authtree = zltreemenu.render('authtree', {
                        checkEnable: true,
                        autoCheckTrigger: true,
                        chkboxType: { "Y": "ps", "N": "s" },
                        radioType: "all",
                        dataurl: layui.cache['contentPath'] + "/manager/coreroleauth/queryAuth?RESRWID=64D83B81B5E845EAA6384A94810A61FF&ORGID=" + $('input[name="ORGIDTEMP"]').val() + "&ROLEID=" + treeNode.RWID,
                        type: "get",
                        idKey: "RESRWID",
                        search: false,
                        dataFilter: function (treeId, parentNode, responseData) {
                            if (responseData[statusName] == OK) {
                                var data = responseData[dataName];
                                return setData(data);
                            }
                            else {
                                zlContext.errorMsg(responseData[msgName]);
                            }
                            return responseData;
                        }
                    }, {
                        onAsyncSuccess: zTreeOnAsyncSuccess
                    })
                }
            })
        }
    })

    // 对应角色的数据表格 函数调用
    inittable();

    // 数据表格中 查看权限 弹窗的树结构渲染所需配置
    var authshowsetting = {
        formtitle: "查看权限",
        view: {
            showLine: true
        },
        async: {
            enable: true,
            url: layui.cache['contentPath'] + "/manager/coreroleauth/queryAuth?RESRWID=64D83B81B5E845EAA6384A94810A61FF",
            type: "get",
            dataFilter: function ajaxDataFilter(treeId, parentNode, responseData) {
                if (responseData[statusName] == OK) {
                    var data = responseData[dataName];
                    return setData(data)
                } else {
                    zlContext.errorMsg(responseData[msgName]);
                }
                return responseData;
            }
        },
        data: {
            key: {
                name: "OBJNAME",
            }
            , simpleData: {
                enable: true
                , idKey: "RESRWID"
                , pIdKey: "SYS_PARENTID"
            }
        }
    };
    function setData(datas) {
        let nodes = [];
        for (var i = 0; i < datas.length; i++) {
            let data = datas[i]
            //排除掉那些没有父亲的节点
            if (data.SYS_PARENTID && nodes.indexOf(data.SYS_PARENTID) == -1) {
                datas.splice(i--, 1);
                continue;
            }
            nodes.push(data.RESRWID);
            if (data.RES_TYPE == "4C5CE7CCD7124C448A82E65B965B36CC") {
                data.icon = layui.cache['contentPath'] + "/static/image/menud.png";
            } else if (data.RES_TYPE == "D0F4A751E3654AB3A714B8A0309D0BCB") {
                data.icon = layui.cache['contentPath'] + "/static/image/menu.png";
            } else if (data.RES_TYPE == "BB8C269F94114CAD8E0FFE530A404C64") {
                data.icon = layui.cache['contentPath'] + "/static/image/btn.png";
            } else if (data.RES_TYPE == "EB7113E02DA643D3B800A03ED2D87C09") {
                data.icon = layui.cache['contentPath'] + "/static/image/hidemenu.png";
            }
            else {
                data.icon = layui.cache['contentPath'] + "/static/image/tab.png";
            }
            if (data.BEIZ != "") {
                data.OBJNAME = data.OBJNAME + '(' + data.BEIZ + ')' + '-[' + data.RESTYPENAME + ']';
            } else {
                data.OBJNAME = data.OBJNAME + '-[' + data.RESTYPENAME + ']';
            }
        };
        return datas;
    }

    function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
        var treeobj = $.fn.zTree.getZTreeObj(treeId),
            node = treeobj.getNodes();
        setInitAuthcheck(node);
        treeobj.refresh();
        layer.close(index);
    }
    function setInitAuthcheck(treenode) {
        for (var i = 0; i < treenode.length; i++) {
            var node = treenode[i];
            if (node.children != undefined) {
                setInitAuthcheck(node.children);
            }
            if (node.AUTH_VALUE == 1) {
                node.checked = true;
            }
        }
    }
    function inittable() {
        usertable = table.render({
            elem: '#tbField'
            , height: 365
            , cellMinWidth: 75
            , limit: 10
            , method: 'post'
            , cols: [[
                { type: 'checkbox', fixed: 'left' }
                , { field: 'USERNAME', width: '125', title: '姓名', sort: true }
                , { field: 'ZHANGHM', width: '100', title: '账号' }
                , { field: 'DEPTNAME', width: '125', title: '部门' }
                , { field: 'ROLENAME', width: '150', title: '角色' }
                , { width: '350', align: 'center', title: '操作', toolbar: '#bar' }
            ]]
            , limit: 20
            , limits: [20, 50, 100, 200, 500, 1000]
            , page: true
            , sortload: true
            , response: zlConfig.global.gridResponse
        });
        zlContext.noData($('#tbField').siblings('div').find('div.layui-table-main'))
    }
    function rendertable() {
        index = layer.msg('数据查询中，请稍候...', { icon: 16, time: false, id: 'dataSearch', shade: 0.1 });
        var keyvalue = $('#keyvalue').val(),
            sNodes = roletree.getSelectedNodes(),
            roleid;
        isloadsearch = keyvalue ? true : false;
        if (sNodes.length > 0) {
            roleid = sNodes[0].RWID;
        } else {
            roleid = "";
        }
        var orgid = $('input[name="ORGIDTEMP"]').val();
        table.reload('tbField', {
            url: layui.cache['contentPath'] + '/manager/coreroleauth/queryUser',
            page: {
                curr: 1  //从第一页开始
            },
            where: { keyvalue: keyvalue, roleid: roleid, orgid: orgid },
            done: function () {
                layer.close(index)
            }
        });
    };

    // 角色树结构 刷新
    $('#resh').on('click', function () {
        // $.fn.zTree.init($("#roletree"), setting, null);
        zltreemenu.render('roletree')
    });
    // 角色树结构 添加
    $('#addrole').on('click', function () {
        var orgid = $('input[name="ORGIDTEMP"]').val();
        var showform = frm.join('');
        showform = showform.replace('#ORGID', orgid);
        formindex = layer.open(
            {
                type: 1,
                content: showform,
                title: '添加角色',
                id: 'addRoleLayer',
                area: ['100%', '100%'],
                success: function (index) {
                    $('input[name="edittype"]').val('add');

                    $('input[name="ORGID"]').val(orgid);
                    // 非通用机构
                    if (orgid != '9C876276D8884BFF94DF343E2A4EED7D') {
                        $('.roletype').show();
                        $('SELECT[name="ROLETYPE"]').val('0');
                        $('SELECT[name="ROLETYPE"]').attr('lay-verify', 'required');
                        form.on('select(ROLETYPE)', function (data) {
                            var value = data.value;
                            if (value == '0') {
                                $('.layui-form-item').show();
                                $('.selRole').hide();
                                $('SELECT[name="MXRWID"]').attr('lay-verify', '');
                                $('input[name="OBJNAME"]').attr('lay-verify', 'required');
                                $('input[name="OBJCODE"]').attr('lay-verify', 'required');
                                $('SELECT[name="ROLELEV"]').attr('lay-verify', 'required');
                            } else {
                                $('.layui-form-item').not('.roletype,.btn').hide();
                                $('SELECT[name="MXRWID"]').attr('lay-verify', 'required');
                                $('input[name="OBJNAME"]').attr('lay-verify', '');
                                $('input[name="OBJCODE"]').attr('lay-verify', '');
                                $('SELECT[name="ROLELEV"]').attr('lay-verify', '');
                                $('.selRole').show();

                            }
                        })
                        // $('SELECT[name="ROLETYPE"]').change(function(){

                        // });
                    }
                    form.render();
                }
            }
        );
    });
    // 角色树结构 删除
    $('#delrole').on('click', function () {
        var orgid;
        var roleid;
        var params = {};
        var selectnode = orgtreeObj.getSelectedNodes();
        var selectrole = roletree.getSelectedNodes();
        if (selectrole.length == 0) {
            zlContext.warnMsg("请先选择角色节点！");
            return;
        }
        if (selectnode.length == 0) {
            orgid = "";
        } else {
            orgid = selectnode[0].RWID;
        }
        roleid = selectrole[0].RWID;
        params = '{"ORGID":"' + orgid + '","ROLEID":"' + roleid + '"}';
        zlContext.confirm('询问', '是否要删除选择的角色吗？', function (index) {
            zlContext.confirm('再次询问', '您真的要删除选择的角色吗？', function (index1) {
                zlContext.deletePost(layui.cache['contentPath'] + '/manager/coreroleauth/delRole', (params), function (result) {
                    if (result[statusName] == OK) {
                        roletree.removeNode(selectrole[0]);
                        roletree.selectNode(roletree.getNodes()[0]);
                        $('#' + roletree.getNodes()[0].tId + '_a').click()
                        zlContext.successMsg('删除角色成功');
                    }
                    else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
                layer.close(index1);
            });
            layer.close(index);
        });
    });
    // 角色树结构 编辑
    $('#editrole').on('click', function () {
        var map = {};
        var selectnode = orgtreeObj.getSelectedNodes();
        var selectrole = roletree.getSelectedNodes();
        if (selectrole.length == 0) {
            zlContext.warnMsg("请先选择角色节点！");
            return;
        }
        var showform = frm.join('');
        formindex = layer.open({
            type: 1,
            content: showform,
            title: '编辑角色',
            success: function (index) {
                $('input[name="edittype"]').val('edit');
                $('input[name="ORGID"]').val($('input[name="ORGIDTEMP"]').val());
                $('input[name="OBJNAME"]').val(selectrole[0].OBJNAME);
                $('input[name="OBJCODE"]').val(selectrole[0].OBJCODE);
                $('input[name="RWID"]').val(selectrole[0].RWID);
                $('input[name="DES"]').val(selectrole[0].DES);
                $('input[name="VISIBILITY"]').val(selectrole[0].VISIBILITY);

                $('select[name="ROLELEV"]').addClass('layui-disabled');
                if (selectnode.length > 0 && selectrole[0].VISIBILITY == 1 && selectnode[0].RWID != "9C876276D8884BFF94DF343E2A4EED7D") {
                    $('select[name="ROLELEV"]').attr('disabled', "disabled");
                    $('input[name="DES"]').addClass('layui-disabled');
                    $('input[name="DES"]').attr('disabled', "disabled");
                    $('input[name="OBJCODE"]').addClass('layui-disabled');
                    $('input[name="OBJCODE"]').attr('disabled', "disabled");
                }

                form.render();
                $('select[name="ROLELEV"]').val(selectrole[0].ROLELEV);
                form.render('select');
            },
            cancel: function (index, layero) {
                newFormObj.newFields = null;
                if ($('#addnew').find('.getField').length == 0) {
                    $('#addnew').append('<button class="layui-btn layui-hide getField" lay-submit lay-filter="addrole">获取表单值</button>');
                }
                var verifyItem = $('#addnew').find('[lay-verify]');
                for (var i = 0; i < verifyItem.length; i++) {
                    var verifyStr = $(verifyItem[i]).attr('lay-verify');
                    if (verifyStr != '') {
                        $(verifyItem[i]).attr({
                            'lay-verify': '',
                            'data-verifyflag': verifyStr
                        })
                    }
                }
                $('#addnew').find('.getField').trigger('click');
                if (newFormObj.newFields == null) {
                    return false;
                }
                newFormObj.newFields.ORGID = selectrole[0].ORGID;
                if (!zlContext.isObjectValueEqual(newFormObj.newFields, selectrole[0])) {
                    var changeConfirmLayer = layer.confirm('数据已有改动，是否要保存？', {
                        title: '是否关闭',
                        resize: false,
                        btn: ['保存关闭', '确定关闭', '取消'], //按钮
                        btnAlign: 'c',
                        anim: 1,
                        icon: 3
                    }, function () {
                        layer.close(changeConfirmLayer)
                        var items = $('#addnew').find('[data-verifyflag]')
                        for (var i = 0; i < items.length; i++) {
                            var verifyStr = $(items[i]).attr('data-verifyflag');
                            $(items[i]).attr({
                                'lay-verify': verifyStr,
                                'data-verifyflag': ''
                            });
                        }
                        $('#btnadd').trigger('click');
                        // obj.sumbit(obj.newFields);
                    }, function () {
                        layer.close(index)
                    }, function () {
                        layer.close(changeConfirmLayer)
                    });
                    return false;
                } else {
                    layer.close(index)
                }
            }
        });
        layer.full(formindex);
    });

    // 数据表格 查询
    $('#search').on('click', function () {
        var sNodes = roletree.getSelectedNodes();
        var tId;
        if (sNodes.length > 0) {
            tId = sNodes[0].RWID;
        } else {
            tId = null;
        }
        rendertable();
    });
    // 数据表格上方 移除人员角色
    $('#btndel').on('click', function () {
        var checkStatus = table.checkStatus('tbField')
            , rows = checkStatus.data;
        if (rows.length == 0) {
            zlContext.warnMsg("请先选择记录！");
            retrun;
        }

        layer.confirm('确定移除选择的人员角色吗？', function (index) {
            layer.close(index);
            zlContext.deletePost(layui.cache['contentPath'] + '/manager/coreroleauth/delUser', rows, function (result) {
                if (result[statusName] == OK) {
                    rendertable();
                    zlContext.successMsg('删除成功');
                }
                else {
                    zlContext.errorMsg(result[msgName]);
                }
            });
        });

    });
    // 数据表格上方 添加人员角色
    $('#btnnew').on('click', function () {
        var selectnode = orgtreeObj.getSelectedNodes();
        if (selectnode.length == 0) {
            zlContext.warnMsg("请先选择机构节点！");
            return;
        }
        var selectrole = roletree.getSelectedNodes();
        if (selectrole.length == 0) {
            zlContext.warnMsg("请先选择角色节点！");
            return;
        }
        var settings = {
            tabs: [
                { tbparams: '{&quot;ORGID&quot;:&quot;' + selectnode[0].RWID + '&quot;,&quot;condition&quot;:&quot;roleid=\'' + selectrole[0].RWID + '\'&quot;}', entryname: 'DEPTID', name: '部门', tableUrl: layui.cache['contentPath'] + '/admin/coreuser/querydeptuser', tbmethod: 'post', url: layui.cache['contentPath'] + '/admin/bddept/querydeptuser?ORGID=' + selectnode[0].RWID, method: 'post' }
            ], id: 'RWID', name: 'OBJNAME', page: 'true', limit: 50, titlefield: 'VALUE', valuefield: 'KEY', buttontype: true, parentnode: '.layui-input-block', container: '.assignment-box', cols: [[
                { type: 'numbers', fixed: 'left', title: '#' }
                , { type: 'checkbox', fixed: 'left' }
                , { field: 'OBJNAME', title: '姓名', width: 100 }
                , { field: 'ZHANGHM', title: '账号', width: 100 }
                , { field: 'OBJCODE', title: '编号', width: 100 }]]
        }
        zlPopSourceExt.onlyshow(settings, function (data) {
            var newdata = {};
            newdata.ORGID = selectnode[0].RWID;
            newdata.ROLEID = selectrole[0].RWID;
            newdata.ROLENAME = selectrole[0].OBJNAME;
            var useridslist = data
                , userids = ''
                , roleids = ''
                , rolenames = ''
                , deptids = ''
                , url = layui.cache['contentPath'] + "/manager/coreroleauth/addUser";
            for (var i = 0; i < useridslist.length; i++) {
                userids = userids + ';' + useridslist[i].RWID;
                roleids = roleids + ';' + useridslist[i].ROLEIDS;
                rolenames = rolenames + ';' + useridslist[i].ROLENS;
                deptids = deptids + ';' + useridslist[i].MNGDEPIDS;
            }
            userids = userids.substr(1, userids.length);
            roleids = roleids.substr(1, roleids.length);
            rolenames = rolenames.substr(1, rolenames.length);
            deptids = deptids.substr(1, deptids.length);

            newdata.USERIDS = userids;
            newdata.ROLEIDS = roleids;
            newdata.ROLENAMES = rolenames;
            newdata.DEPTIDS = deptids;
            $.post(
                url,
                newdata,
                function (data) {
                    data = eval('(' + data + ')');
                    if (data.state == 'OK') {
                        rendertable();
                        zlContext.successMsg('保存成功');
                    } else {
                        zlContext.errorMsg(data.msg);
                    }
                }
            );
        });
    });

    // 角色树结构 添加弹窗中的 form 表单提交
    form.on('submit(addrole)', function (data) {
        if ($(data.elem).hasClass('getField')) {
            newFormObj.newFields = data.field
            return false;
        }
        var url = layui.cache['contentPath'] + "/manager/coreroleauth/addRole";
        var edittype = $('input[name="edittype"]').val();
        if (edittype == 'edit') {
            url = layui.cache['contentPath'] + "/manager/coreroleauth/modifyRole";
        } else if (data.field.ROLETYPE == "1") {
            url = layui.cache['contentPath'] + "/manager/coreroleauth/modifyRoleMx";
        }
        zlContext.post(
            url,
            data.field,
            function (data) {
                if (data[statusName] == OK) {
                    layer.close(formindex);
                    roletree = zltreemenu.render('roletree')
                    zlContext.successMsg('保存成功');
                } else {
                    zlContext.errorMsg(data[msgName]);
                }
            });
        return false;
    });
    // 数据表格上方 添加人员角色弹窗中的 form 表单提交
    form.on('submit(adduser)', function (data) {
        url = layui.cache['contentPath'] + "/manager/coreroleauth/addUser";
        $.post(
            url,
            data.field,
            function (data) {
                layer.close(formindex);
                data = eval('(' + data + ')');
                if (data.state == 'OK') {
                    rendertable();
                    zlContext.successMsg('添加人员角色成功！');
                } else {
                    zlContext.errorMsg(data.msg);
                }
            }
        );
        return false;
    });

    table.on('tool(tbField)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            , layEvent = obj.event //获得 lay-event 对应的值
            , list = new Array();
        list.push(data);
        if (layEvent === 'detail') {
            showauthform(data.RWID, data.ROLEID, data.DEPTID == undefined ? "" : data.DEPTID, data.ORGID, data.USERDEPTID == undefined ? "" : data.USERDEPTID);
        } else if (layEvent === 'del') {
            var msg = '是否要移除【' + data.USERNAME + '】在【' + data.DEPTNAME + '】的【' + data.ROLENAME + '】角色？';
            if (!data.DEPTNAME) {
                msg = '是否要移除【' + data.USERNAME + '】的【' + data.ROLENAME + '】角色？';
            }
            layer.confirm(msg, function (index) {
                layer.close(index);
                zlContext.deletePost(layui.cache['contentPath'] + '/manager/coreroleauth/delUser', list, function (result) {
                    if (result[statusName] == OK) {
                        obj.del(); //删除对应行（tr）的DOM结构
                        zlContext.successMsg('移除人员角色成功！');
                    }
                    else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
            });
        } else if (layEvent === 'edit') {
            userauthedit(data);
        } else if (layEvent === 'delauto') {
            var coreuserdept = {};
            coreuserdept.RWID = data.USERDEPTID == undefined ? "" : data.USERDEPTID;
            coreuserdept.ROLEID = data.ROLEID;
            coreuserdept.ORGID = data.ORGID;
            coreuserdept.USERID = data.RWID;

            layer.confirm('确定移除该用户角色的权限吗?移除用户角色的权限之后该用户角色将继承角色权限', function (index) {
                layer.close(index);
                zlContext.deletePost(layui.cache['contentPath'] + '/manager/coreroleauth/removeauth', coreuserdept, function (result) {
                    if (result[statusName] == OK) {
                        zlContext.successMsg('移除用户角色权限成功！');
                    }
                    else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
            });
        }
    });

    function userauthedit(obj) {
        // 数据表格中 对应账号编辑权限弹窗的 树结构渲染所需配置
        var usesetting = {
            view: {
                showLine: true
            },
            async: {
                enable: true,
                url: layui.cache['contentPath'] + "/manager/coreroleauth/queryAuth?RESRWID=64D83B81B5E845EAA6384A94810A61FF",
                type: "get",
                dataFilter: function ajaxDataFilter(treeId, parentNode, responseData) {
                    if (responseData[statusName] == OK) {
                        var data = responseData[dataName];
                        return setData(data);
                    }
                    else {
                        zlContext.errorMsg(responseData[msgName]);
                    }
                    return responseData;
                },
                otherParam: { USERID: obj.RWID, DEPTID: obj.DEPTID, ORGID: obj.ORGID, ROLEID: obj.ROLEID, ROLE_DEP_ID: obj.USERDEPTID }
            },
            data: {
                key: {
                    name: "OBJNAME"
                }
                , simpleData: {
                    enable: true
                    , idKey: "RESRWID"
                    , pIdKey: "SYS_PARENTID"
                    , rootPid: ""
                }
            },
            check: {
                enable: true,
                chkboxType: { "Y": "ps", "N": "s" },
                chkStyle: "checkbox",
            },
            callback: {
                onAsyncSuccess: zTreeOnAsyncSuccess
            }
        };
        var html = ['<div class="layui-form">'
            , '<ul id="userauthtree" class="ztree layui-card-body" style="height: 385px;width:98%"></ul>'
            , '</div>'];
        var authtreeObj = null;
        layer.open({
            type: 1,
            id: 'editAuthLayer',
            area: ['500px', '500px'],
            content: html.join(''),
            title: '编辑权限',
            btn: ['确定', '取消'],
            success: function () {
                authtreeObj = $.fn.zTree.init($("#userauthtree"), usesetting, null);
            },
            yes: function (index) {
                var authtree = $.fn.zTree.getZTreeObj("userauthtree")
                    , autonode = authtree.getNodes()
                    , autonodes = authtree.transformToArray(autonode)
                    , coreauthlist = new Array();
                for (var i = 0; i < autonodes.length; i++) {
                    var node = autonodes[i];
                    if ((node.checked && node.AUTH_VALUE != 1) || (!node.checked && node.AUTH_VALUE == 1)) {
                        var coreauth = {};
                        coreauth.ROLEID = obj.ROLEID;
                        coreauth.ORGID = obj.ORGID;
                        coreauth.ROLE_DEP_ID = obj.USERDEPTID;
                        coreauth.DEPTID = obj.DEPTID;
                        coreauth.USERID = obj.RWID;
                        coreauth.RES_ID = node.RESRWID;
                        coreauth.AUTH_VALUE = node.checked ? 1 : 0;
                        coreauth.AUTH_TYPE = 0;
                        coreauthlist.push(coreauth);
                        node.AUTH_VALUE = coreauth.AUTH_VALUE;
                        authtree.updateNode(node);
                    }
                };

                zlContext.post(layui.cache['contentPath'] + "/manager/coreroleauth/addAuth", coreauthlist, function (data) {
                    if (data.state == OK) {
                        layer.close(index);
                        zlContext.successMsg("保存成功！");
                    } else {
                        zlContext.errorMsg(data.msg);
                    }
                }
                );
            },
            cancel: function (index, layero) {
                var changedCheckedNodes = authtreeObj.getChangeCheckedNodes().length;

                if (changedCheckedNodes > 0) {
                    var changeConfirmLayer = layer.confirm('数据已有改动，是否要保存？', {
                        title: '是否关闭',
                        resize: false,
                        btn: ['保存关闭', '确定关闭', '取消'], //按钮
                        btnAlign: 'c',
                        anim: 1,
                        icon: 3
                    }, function () { // 保存关闭
                        layer.close(changeConfirmLayer)
                        layero.find('a.layui-layer-btn0').trigger('click')
                    }, function () { // 确定关闭
                        layer.close(index)
                    }, function () { // 取消
                        layer.close(changeConfirmLayer)
                    });
                } else {
                    layer.close(index)
                }
                return false;
            }
        });
    };

    $('#btnsave').on('click', function () {
        var selectnode = roletree.getSelectedNodes()
            , row = table.checkStatus('tbField').data
            , selectorgnode = orgtreeObj.getSelectedNodes()
            , autonode = authtree.getNodes()
            , autonodes = authtree.transformToArray(autonode)
            , coreauthlist = new Array()
            , param;
        if (selectnode.length == 0) {
            zlContext.warnMsg('请先选择角色');
            return;
        }
        var ROLEID = selectnode[0].RWID
            , ORGID = selectorgnode.length == 0 ? "" : selectorgnode[0].RWID
            , ROLEDEPTID = '';
        for (var i = 0; i < row.length; i++) {
            ROLEDEPTID = ROLEDEPTID + "," + row[i].USERDEPTID;
        }
        ROLEDEPTID = ROLEDEPTID.substr(1, ROLEDEPTID.length);
        for (var i = 0; i < autonodes.length; i++) {
            var node = autonodes[i];
            if ((node.checked && node.AUTH_VALUE != 1) || (!node.checked && node.AUTH_VALUE == 1) || ROLEDEPTID != "") {
                var coreauth = {};
                coreauth.ROLEID = ROLEID;
                coreauth.ORGID = ORGID;
                coreauth.ROLE_DEP_ID = ROLEDEPTID;
                coreauth.RES_ID = node.RESRWID;
                coreauth.AUTH_VALUE = node.checked ? 1 : 0;
                coreauth.AUTH_TYPE = 0;
                coreauthlist.push(coreauth);
                node.AUTH_VALUE = coreauth.AUTH_VALUE;
                authtree.updateNode(node);
            }
        };
        // param = JSON.stringify(coreauthlist);

        zlContext.post(layui.cache['contentPath'] + "/manager/coreroleauth/addAuth", coreauthlist, function (data) {
            if (data.state == OK) {
                zlContext.successMsg("保存成功！");
            } else {
                zlContext.errorMsg(data.msg);
            }
        }
        );

    });
    $('#expand').on('click', function () {
        authtree.expandAll(true);
    });
    $('#unexpand').on('click', function () {
        authtree.expandAll(false);
    });
    $('#checkall').on('click', function () {
        authtree.checkAllNodes(true);
    })
    $('#uncheck').on('click', function () {
        var allnode = authtree.getNodes();
        setoppositecheck(allnode);
        authtree.refresh();
    });
    $('#export').on('click', function () {
        var orgid;
        var selectnode = orgtreeObj.getSelectedNodes();
        if (selectnode.length == 0) {
            orgid = "";
        } else {
            orgid = selectnode[0].RWID;
        }
        var params = {};
        params.orgid = orgid;
        var index = layer.load();
        $.post(layui.cache['contentPath'] + "/manager/coreroleauth/exportsqlfile", params, function (data) {
            layer.close(index);
            data = eval('(' + data + ')');
            if (data.state == OK) {
                location.href = encodeURI(encodeURI(layui.cache['contentPath'] + "/static/appdata/Download/" + data.obj));
            } else {
                zlContext.errorMsg(data.msg);
            }
        }
        );
    });
    $("#keyvalue").keyup(function () {
        var e = event || window.event;
        if (e.keyCode == 13) {
            $("#search").trigger("click");
        }
        if ((e.keyCode == '46' || e.keyCode == '8' || (e.ctrlKey && e.keyCode == '86')) && $(this).val() == '' && isloadsearch) {
            $('#search').trigger('click');
            isloadsearch = false;
        }
    });

    function setoppositecheck(treenode) {
        for (var i = 0; i < treenode.length; i++) {
            var node = treenode[i];
            if (node.children != undefined) {
                setoppositecheck(node.children);
            }
            if (node.checked) {
                node.checked = false;
            } else {
                node.checked = true;
            }
        }
    }
    function showauthform(USERID, ROLEID, DEPTID, ORGID, USERDEPTID) {
        authshowsetting.async.otherParam = { USERID: USERID, DEPTID: DEPTID, ORGID: ORGID, ROLEID: ROLEID, ROLE_DEP_ID: USERDEPTID, AUTH_VALUE: 1 }
        // authshowsetting.async.url = layui.cache['contentPath'] + "/manager/coreroleauth/queryAuth",
        zlpoptree.onlyshow(authshowsetting);
    }


    $(window).on('resize', function () {
        zlContext.setMaxHeihgt(0);
        resizeFunction(32, 20, 365);
        var $dockingtopH = parseFloat($(".docking-top").height());
        var $dockingbottomH = parseFloat($(".docking-bottom").height());
        var $dockingfillH = parseFloat($(".docking-fill").height());
        if ($dockingtopH + $dockingbottomH > $dockingfillH) {
            $(".docking-fill").removeClass("docking-fill");
        } else {
            $(".docking-fill").addClass("docking-fill");
        }
    }).resize();

    // 窗口大小变化事件，filldeff用于求".docking-fill"元素的高差值，condeff用于求".zl-container"的高差值
    function resizeFunction(filldeff, condeff, tableheight) {
        var windowH = $(window).height(),
            zlcontainerH,
            topzltoolbar = $(".docking-top .zl-toolbar"),
            bottomzltoolbar = $(".docking-bottom .zl-toolbar"),
            dockingtopmb = parseFloat($(".docking-top").css("margin-bottom")),
            topzltoolbarH = topzltoolbar.height() + parseFloat(topzltoolbar.css("margin-bottom"));
        bottomzltoolbarH = bottomzltoolbar.height() + parseFloat(bottomzltoolbar.css("margin-bottom"));
        $(".docking-bottom").height(windowH - dockingtopmb - topzltoolbarH - tableheight - filldeff);
        $(".docking-bottom .zl-container").height($(".docking-bottom").height() - condeff - bottomzltoolbarH);
        return zlcontainerH = $(".docking-bottom").height() - condeff - bottomzltoolbarH;
    }

    // frm 为新建和编辑角色时 弹窗的html内容
    var frm = ['<div class="site-block"><form class="layui-form " id="addnew" >'
        , '   <div class="layui-form-item roletype" style="display:none">'
        , '       <div class="layui-col-md12">'
        , '           <label class="layui-form-label">新增类型</label>'
        , '           <div class="layui-input-block">'
        , '               <select name="ROLETYPE" value="0" lay-filter="ROLETYPE">'
        , '                   <option value=""></option>'
        , '                   <option value="0">新增个性角色</option>'
        , '                   <option value="1">新增已删除角色</option>'
        , '               </select>'
        , '            </div>'
        , '       </div>'
        , '   </div>'
        , '   <input type="hidden" name="ORGID">'
        , '   <input type="hidden" name="edittype">'
        , '   <input type="hidden" name="RWID">'
        , '   <input type="hidden" name="VISIBILITY">'
        , '   <div class="layui-form-item">'
        , '       <div class="layui-col-md12 ">'
        , '           <label class="layui-form-label">名称</label>'
        , '           <div class="layui-input-block">'
        , '               <input type="text" class="layui-input" lay-filter="OBJNAME" name="OBJNAME" maxlength="13" lay-verify="required">'
        , '           </div>'
        , '       </div>'
        , '   </div>'
        , '   <div class="layui-form-item">'
        , '       <div class="layui-col-md12 ">'
        , '           <label class="layui-form-label">编号</label>'
        , '           <div class="layui-input-block">'
        , '               <input type="text" class="layui-input" lay-filter="OBJCODE" name="OBJCODE" maxlength="3" lay-verify="required|number">'
        , '            </div>'
        , '       </div>'
        , '   </div>'
        , '   <div class="layui-form-item">'
        , '       <div class="layui-col-md12">'
        , '           <label class="layui-form-label">描述</label>'
        , '           <div class="layui-input-block">'
        , '               <input type="text" class="layui-input" lay-filter="ICON_SMALL" name="DES" maxlength="166">'
        , '            </div>'
        , '       </div>'
        , '   </div>'
        , '   <div class="layui-form-item">'
        , '       <div class="layui-col-md12">'
        , '           <label class="layui-form-label">角色级别</label>'
        , '           <div class="layui-input-block">'
        , '               <select lay-verify="required" name="ROLELEV">'
        , '                   <option value=""></option>'
        , '                   <option value="0">部门级别</option>'
        , '                   <option value="1">机构级别</option>'
        , '               </select>'
        , '            </div>'
        , '       </div>'
        , '   </div>'
        , '   <div class="layui-form-item selRole" style="display:none">'
        , '       <div class="layui-col-md12">'
        , '           <label class="layui-form-label">选择已删除角色</label>'
        , '           <div class="layui-input-block">'
        , '		         <select name="MXRWID" lay-filter="RES_TYPE"  placeholder="请选择已删除角色" zlcomponent class="select-ext" settings="{titlefield: \'OBJNAME\', valuefield: \'MXRWID\',dataurl:\'' + layui.cache['contentPath'] + '/manager/coreroleauth/queryUnuseRole?ORGID=#ORGID' + '\'}">'
        , '		         </select>'
        , '            </div>'
        , '       </div>'
        , '   </div>'
        , '   <div class="layui-form-item btn">'
        , '       <div class="layui-input-block">'
        , '           <button class="layui-btn "  id="btnadd" lay-submit  lay-filter="addrole">保存</button>'
        , '       </div>'
        , '   </div>'
        , '</form></div>'
    ];
});